package com.xo.xodemo.controller.system;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xo.xodemo.common.Result;
import com.xo.xodemo.mapper.db1.DepartmentMapper;
import com.xo.xodemo.mapper.db1.PositionMapper;
import com.xo.xodemo.mapper.db1.UserMapper;
import com.xo.xodemo.model.*;
import com.xo.xodemo.springsecurityconfig.CustomUserDetails;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PositionMapper positionMapper;



    @RequestMapping("add")
    @ResponseBody
    public Result add(Model model, BaseUser baseUser) {
        BaseUser baseUser1=userMapper.loadUserByUsername(baseUser.getUsername());
        BaseUser baseUser2=userMapper.selectByemployeeNumber(baseUser.getEmployeeNumber());
        //如果这个用户名已经被用了
        if(baseUser1!=null){
            return  Result.error("用户名已被使用");
        }
        if(baseUser2!=null){
            return  Result.error("用户编码已被使用");
        }
        else {
            baseUser.setPassword(new BCryptPasswordEncoder().encode(baseUser.getPassword()));
            userMapper.insertuser(baseUser);
            return  Result.success();
        }


    }
    @RequestMapping("delete")
    @ResponseBody
    public Result delete(@Param("userId") String userId) {
        userMapper.deleteUser(userId);
        return  Result.success();

    }
    @RequestMapping("update")
    @ResponseBody
    public Result update(String realName,String password) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        if(!StringUtils.isEmpty(password)){
          password=new BCryptPasswordEncoder().encode(password);
        }
        userMapper.updateBySelf(currentUserName,password,realName);
        return  Result.success();

    }
    @RequestMapping("query")
    @ResponseBody
    public Result query(@Param("page") Integer page, @Param("limit")Integer limit, @Param("username") String username) {
        PageInfo pageInfo=null;
        if (!StringUtils. isEmpty(username)) {
            PageHelper.startPage(page,limit);
             pageInfo=new PageInfo(userMapper.selectAllByName(username));
        }
        else {
            PageHelper.startPage(page,limit);
            pageInfo=new PageInfo(userMapper.selectAll());
        }
        return   Result.success( pageInfo);

    }
    @RequestMapping("queryforselect")
    @ResponseBody
    public Result queryforselect() {
        return   Result.success(userMapper.selectAll());

    }
    @RequestMapping("updaterealname")
    @ResponseBody
    public Result updaterealname(@RequestParam("realname") String realname,@AuthenticationPrincipal CustomUserDetails userDetails) {
        userMapper.updateRealName(realname,userDetails.getUsername());
        return   Result.success( );

    }
//    根据userId修改除了密码外的用户信息(现在密码也能改，不能改用户名）
    @RequestMapping("updateUserExceptPassword")
    @ResponseBody
    public Result  updateUserExceptPassword(BaseUser baseUser){
        BaseUser baseUser2=userMapper.selectByemployeeNumber(baseUser.getEmployeeNumber());
        if (baseUser2 != null){
            if(Objects.equals(baseUser.getUserId(), baseUser2.getUserId())){
                if (Objects.equals(baseUser.getEmployeeNumber(), baseUser2.getEmployeeNumber())){
                    baseUser.setEmployeeNumber(null);
                }
                baseUser2 = null;
            }
        }
        if(baseUser2!=null){
            return  Result.error("用户编码已被使用");
        }
        else {
            //修改密码
            String password =  baseUser.getPassword();
            if(password!=null&&password.length()>0){
                userMapper.updatePassword(new BCryptPasswordEncoder().encode(password),baseUser.getUsername());
            }
            //修改密码以外的用户信息
            userMapper.updateUserExceptPassword(baseUser.getRealName(),
                    baseUser.getPositionId(),baseUser.getDepartmentId(),baseUser.getEmployeeNumber(),
                    baseUser.getUserId(),baseUser.getIsIncumbency());


            return  Result.success();
        }
    }
    //通过username修改用户的在职状态
    @RequestMapping("updateIsIncumbencyByUserName")
    @ResponseBody
    public Result updateIsIncumbencyByUserName(@Param(value = "username") String username,@Param(value = "isIncumbency") Integer isIncumbency){
        userMapper.updateIsIncumbencyByUserName(username,isIncumbency);
        return Result.success();
    }
    //根据用户名查找用户的在职状态
    @RequestMapping("selectIsIncumbencyByUserName")
    @ResponseBody
    public Integer selectIsIncumbencyByUserName(@Param(value = "username") String username){
        Integer isIncumbency = -1;
        if (username != null){
          isIncumbency =  userMapper.selectIsIncumbencyByUserName(username);
        }
        return isIncumbency;
    }
    @RequestMapping("updatepassword")
    @ResponseBody
    public Result updatepassword(@RequestParam("password") String password,@AuthenticationPrincipal CustomUserDetails userDetails) {
        if(password!=null&&password.length()>0){
            userMapper.updatePassword(new BCryptPasswordEncoder().encode(password),userDetails.getUsername());
        }
        return   Result.success();

    }
    //查找权限列表,给下拉框用的
    @RequestMapping("/positionquery")
    @ResponseBody
    public List<Position> positionquery() {
        return   positionMapper.findAll();

    }

    //权限管理详情页面
    @RequestMapping("/positiondetailquery")
    @ResponseBody
    public Result positiondetailquery() {
        return   Result.success(userMapper.findproofbargainfirstauditinguser());

    }
    //查找具有成交单初次审核权限的
    @RequestMapping("/findproofbargainfi rstauditinguser")
    @ResponseBody
    public   Result findproofbargainfirstauditinguser() {
        return   Result.success(userMapper.findproofbargainfirstauditinguser());
    }
}
